using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using System.IO;
 
/// <summary>
/// MD5工具
/// </summary>
public static class MD5Utils
{
    /// <summary>
    /// 文件是否有修改
    /// </summary>
    public static bool HaveModify(string curMD5, string preMD5)
    {
        StringComparer comparer = StringComparer.OrdinalIgnoreCase;
        return comparer.Compare(curMD5, preMD5) != 0;
    }
 
    /// <summary>
    /// 得到MD5(通过内容)
    /// </summary>
    public static string GetMD5(string content)
    {
        if (string.IsNullOrEmpty(content))
        {
            Debug.LogError("文件内容为空");
            return "";
        }
 
        byte[] contentBytes = Encoding.UTF8.GetBytes(content);
        return GetMD5(contentBytes);
    }
 
    /// <summary>
    /// 得到MD5(通过文件)
    /// </summary>
    public static string GetMD5(FileStream stream)
    {
        MD5 md5 = MD5.Create();
        md5 = new MD5CryptoServiceProvider();
        byte[] targetData = md5.ComputeHash(stream);
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < targetData.Length; i++)
        {
            strBuilder.AppendFormat("{0:x2}", targetData[i]);
        }
        return strBuilder.ToString();
    }
 
    /// <summary>
    /// 得到MD5(通过字节数组)
    /// </summary>
    static string GetMD5(byte[] data)
    {
        MD5 md5 = MD5.Create();
        md5 = new MD5CryptoServiceProvider();
        byte[] targetData = md5.ComputeHash(data);
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < targetData.Length; i++)
        {
            strBuilder.AppendFormat("{0:x2}", targetData[i]);
        }
        return strBuilder.ToString();
    }
}